package cn.edu.tju.elm.controller.user;

import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.elm.model.Food;
import cn.edu.tju.elm.service.FoodService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户端商品控制器
 * 仅为普通用户提供商品浏览功能
 * 使用完整的FoodService，但只调用查询方法
 */
@RestController
@RequestMapping("/api/public/foods")
@Tag(name = "用户商品浏览", description = "普通用户商品浏览功能")
public class UserFoodController {

    @Autowired
    private FoodService foodService;

    @GetMapping("/business/{businessId}")
    @Operation(summary = "获取商家商品列表", description = "获取指定商家的所有商品")
    public HttpResult<List<Food>> getFoodsByBusiness(
            @Parameter(description = "商家ID", required = true) @PathVariable Long businessId) {
        try {
            // 直接返回服务层的结果
            return foodService.getFoodsByBusinessId(businessId);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, 
                    "获取商品列表失败: " + e.getMessage());
        }
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取商品详情", description = "根据ID获取商品详细信息")
    public HttpResult<Food> getFoodById(
            @Parameter(description = "商品ID", required = true) @PathVariable Long id) {
        try {
            // 直接返回服务层的结果
            return foodService.getFoodById(id);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, 
                    "获取商品详情失败: " + e.getMessage());
        }
    }

    @GetMapping("/search")
    @Operation(summary = "搜索商品", description = "根据关键词搜索商品")
    public HttpResult<List<Food>> searchFoods(
            @Parameter(description = "搜索关键词") @RequestParam String keyword,
            @Parameter(description = "商家ID（可选）") @RequestParam(required = false) Long businessId) {
        try {
            List<Food> allFoods;
            
            if (businessId != null) {
                // 在指定商家内搜索
                HttpResult<List<Food>> result = foodService.getFoodsByBusinessId(businessId);
                if (!result.getSuccess()) {
                    // 修正：使用正确的 failure 方法
                    return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, result.getMessage());
                }
                allFoods = result.getData();
            } else {
                // 全局搜索
                HttpResult<List<Food>> result = foodService.getAllFoods();
                if (!result.getSuccess()) {
                    // 修正：使用正确的 failure 方法
                    return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, result.getMessage());
                }
                allFoods = result.getData();
            }
            
            // 使用Java流进行内存中过滤（适用于小规模数据）
            List<Food> filteredFoods = allFoods.stream()
                .filter(food -> 
                    food.getFoodName() != null && food.getFoodName().toLowerCase().contains(keyword.toLowerCase()) ||
                    food.getFoodExplain() != null && food.getFoodExplain().toLowerCase().contains(keyword.toLowerCase())
                )
                .collect(Collectors.toList());
            
            return HttpResult.success(filteredFoods);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, 
                    "搜索商品失败: " + e.getMessage());
        }
    }

    @GetMapping("")
    @Operation(summary = "获取所有商品", description = "获取系统中的所有商品（分页可选）")
    public HttpResult<List<Food>> getAllFoods(
            @Parameter(description = "页码") @RequestParam(required = false, defaultValue = "0") int page,
            @Parameter(description = "每页大小") @RequestParam(required = false, defaultValue = "20") int size) {
        try {
            HttpResult<List<Food>> result = foodService.getAllFoods();
            if (!result.getSuccess()) {
                // 修正：使用正确的 failure 方法
                return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, result.getMessage());
            }
            
            List<Food> foods = result.getData();
            
            // 简单分页实现（生产环境中应使用Repository的分页查询）
            int fromIndex = Math.min(page * size, foods.size());
            int toIndex = Math.min(fromIndex + size, foods.size());
            List<Food> pagedFoods = foods.subList(fromIndex, toIndex);
            
            return HttpResult.success(pagedFoods);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, 
                    "获取商品列表失败: " + e.getMessage());
        }
    }
}